import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_tap.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/follow_model.dart';

/// 关注粉丝页面类型枚举
enum SocialConnectionType {
  following('Follow List'),
  followers('Fan List');

  const SocialConnectionType(this.displayName);
  final String displayName;
}

/// 关注粉丝页面视图模型
class SocialConnectionNavigatorViewModel extends BaseViewModel {
  SocialConnectionType _pageType = SocialConnectionType.following;
  SocialConnectionType get pageType => _pageType;

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化页面类型
  void initializePageType(SocialConnectionType type) {
    _pageType = type;
    notifyListeners();
  }

  /// 获取用户列表
  List<UserModel> get userList {
    if (!isLoggedIn || currentUser == null) return [];

    List<FollowRelationModel> relations;
    if (_pageType == SocialConnectionType.following) {
      relations = appState.followManager.fetchFollowingList(currentUser!.id);
    } else {
      relations = appState.followManager.fetchFollowersList(currentUser!.id);
    }

    return relations
        .map((relation) {
          final userId =
              _pageType == SocialConnectionType.following
                  ? relation.followingId
                  : relation.followerId;
          return appState.userStore.getUserById(userId);
        })
        .where((user) => user != null)
        .cast<UserModel>()
        .toList();
  }

  /// 检查是否已关注某个用户
  bool isUserFollowed(String targetUserId) {
    if (!isLoggedIn || currentUser == null) return false;
    return appState.followManager.isFollowing(currentUser!.id, targetUserId);
  }

  /// 切换关注状态
  Future<void> toggleFollowStatus(
    String targetUserId,
    BuildContext context,
  ) async {
    if (!isLoggedIn || currentUser == null) {
      MagmaToast.warning(context, title: 'Please login first');
      return;
    }

    final isCurrentlyFollowing = isUserFollowed(targetUserId);

    if (isCurrentlyFollowing) {
      // 取消关注
      final success = await appState.followManager.terminateFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );

      if (success) {
        MagmaToast.success(context, title: 'Unfollowed successfully');
      } else {
        MagmaToast.error(context, title: 'Failed to unfollow');
      }
    } else {
      // 关注用户
      final success = await appState.followManager.establishFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );

      if (success) {
        MagmaToast.success(context, title: 'Followed successfully');
      } else {
        MagmaToast.error(context, title: 'Failed to follow');
      }
    }

    notifyListeners();
  }
}

/// 关注粉丝页面
class FollowFanStory extends StatefulWidget {
  final String pageType;

  const FollowFanStory({super.key, required this.pageType});

  @override
  State<FollowFanStory> createState() => _FollowFanStoryState();
}

class _FollowFanStoryState extends State<FollowFanStory> {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<SocialConnectionNavigatorViewModel>.reactive(
      viewModelBuilder: () => SocialConnectionNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        // 根据传入的参数确定页面类型
        final type =
            widget.pageType == 'followers'
                ? SocialConnectionType.followers
                : SocialConnectionType.following;
        viewModel.initializePageType(type);
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 标题栏
                  _buildTitleBar(viewModel),

                  // 内容区域
                  Expanded(
                    child:
                        viewModel.isLoggedIn
                            ? _buildUserList(viewModel)
                            : _buildLoginPrompt(),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildTitleBar(SocialConnectionNavigatorViewModel viewModel) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          MagmaTap(
            onTap: () => QR.back(),
            child: Image.asset(
              MagmaConstant.back,
              width: 20.w,
              height: 20.w,
              color: MagmaColor.white,
            ),
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text(viewModel.pageType.displayName).blackHanSans(
                fontSize: 24.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          SizedBox(width: 32.w),
        ],
      ),
    );
  }

  /// 构建用户列表
  Widget _buildUserList(SocialConnectionNavigatorViewModel viewModel) {
    final users = viewModel.userList;

    if (users.isEmpty) {
      return Center(
        child: Text(
          viewModel.pageType == SocialConnectionType.following
              ? 'No following yet'
              : 'No followers yet',
        ).inter(fontSize: 16.sp, color: MagmaColor.white.withOpacity(0.6)),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 118 / 157, // 118:157 包含头像超出部分的总高度 (134 + 23)
          crossAxisSpacing: 12.w,
          mainAxisSpacing: 20.h,
        ),
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];
          return _buildUserCard(user, viewModel);
        },
      ),
    );
  }

  /// 构建用户卡片
  Widget _buildUserCard(
    UserModel user,
    SocialConnectionNavigatorViewModel viewModel,
  ) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        // 卡片主体（118:134宽高比）
        Positioned(
          top: 23.h,
          left: 0,
          right: 0,
          child: Container(
            width: 118.w,
            height: 134.h,
            decoration: BoxDecoration(
              color: MagmaColor.black,
              borderRadius: BorderRadius.circular(8.r),
              border: Border.all(color: MagmaColor.white, width: 1.w),
            ),
            child: Padding(
              padding: EdgeInsets.only(top: 45.h),
              child: Column(
                children: [
                  // 用户名
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 8.w),
                    child: Text(
                      user.username,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ).inter(
                      fontSize: 17.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),

                  Spacer(),

                  // 关注按钮
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 8.w),
                    child: _buildFollowButton(user, viewModel),
                  ),

                  Spacer(),
                ],
              ),
            ),
          ),
        ),

        // 头像（部分超出顶部）
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Center(
            child: CircleAvatar(
              radius: 33.r,
              backgroundImage: AssetImage(user.avatar),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建关注按钮
  Widget _buildFollowButton(
    UserModel user,
    SocialConnectionNavigatorViewModel viewModel,
  ) {
    final isFollowing = viewModel.isUserFollowed(user.id);

    return MagmaTap(
      onTap: () => viewModel.toggleFollowStatus(user.id, context),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 7.h),
        decoration: BoxDecoration(
          color:
              isFollowing
                  ? MagmaColor.grey.withOpacity(0.3)
                  : MagmaColor.purple,
          borderRadius: BorderRadius.circular(23.5.r),
          border: Border.all(color: const Color(0xFFC29FFD), width: 1.w),
        ),
        child: Center(
          child: Text(
            isFollowing ? 'Unfollow' : 'Follow',
            style: TextStyle(
              fontSize: 16.sp,
              color: MagmaColor.white,
              fontFamily:
                  GoogleFonts.rowdies(fontWeight: FontWeight.w400).fontFamily,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建登录提示
  Widget _buildLoginPrompt() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Logo
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(MagmaConstant.logo, width: 120.w, height: 120.w),
          ),

          SizedBox(height: 32.h),

          // 提示文字
          Text(
            'Please login to view your connections',
            textAlign: TextAlign.center,
          ).inter(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w600,
          ),

          SizedBox(height: 16.h),

          Text(
            'Connect with friends and build your network',
            textAlign: TextAlign.center,
          ).inter(
            fontSize: 14.sp,
            color: MagmaColor.white.withOpacity(0.7),
            fontWeight: FontWeight.w400,
          ),

          SizedBox(height: 40.h),

          // 登录按钮
          MagmaTap(
            onTap: () => QR.to(MagmaRouter.loginPath),
            child: Container(
              width: 200.w,
              height: 56.h,
              decoration: BoxDecoration(
                color: MagmaColor.purple,
                borderRadius: BorderRadius.circular(28.r),
              ),
              child: Center(
                child: Text('Login').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.black,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
